package com.yc.lock;

public class Test3 {
    //创建静态的”空对象“
    public static Object obj1=new Object();
    public static Object obj2=new Object();

    public static void main(String[] args) {
        //创建进程对象
        Thread t1 = new Thread(new C());
        Thread t2 = new Thread(new D());
        //执行线程里的方法
        t1.start();
        t2.start();
    }
}
/**
 *实现线程接口的类
 */
class C implements  Runnable{
    @Override
    public void run(){
        //加同步锁,锁住对象1
        synchronized (Test3.obj1){
            System.out.println("对象1被锁住");
            try {
                //让线程睡眠，占有对象1的资源2秒钟，目的：为了给另外的线程充分的时间来竞争该资源
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            try {
                //执行完后，主动释放资源
                Test3.obj1.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            synchronized (Test3.obj2){
                System.out.println("锁住对象2");
            }
        }
    }
}
class D implements  Runnable{
    @Override
    public void run(){
        //加同步锁,锁住对象2
        synchronized (Test3.obj2){
            System.out.println("对象2被锁住");
            try {
                //让线程睡眠，占有对象2的资源1秒钟，目的：为了给另外的线程充分的时间来竞争该资源
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            synchronized (Test3.obj1){
                //再次唤醒线程抢占资源
                Test3.obj1.notify();
                System.out.println("锁住对象1");
            }
        }
    }

}
